#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>

typedef int elementype;

typedef struct node{
	elementype data;
	struct node *next;
}stacknode, *linkstackptr;
typedef struct stack{
	linkstackptr top;		//栈顶指针 
	int count;				//计数器 
}Linkstack;

// 判断栈S是否为空栈，只判断栈顶元素即可，返回true/fales
int stackempty(Linkstack S)
{ 
        if (S.count == 0)
                return 1;
        else
                return 0;
}

// 入栈
bool push(Linkstack *S, elementype e)		
{
	linkstackptr s = (linkstackptr)malloc(sizeof(stacknode));
	s -> data = e;
	s -> next = S -> top;		//把当前的栈顶赋值给新的元素的后继(指针的指向)
	S -> top = s;		//新的节点赋值给栈顶指针（即让新元素成为栈顶元素）
	S -> count++;
	return true; 
}

//出栈操作(栈顶指针->p，指针后移，释放节点，计数器自减)
int pop(Linkstack *s, elementype *e)		
{
	linkstackptr p;		//临时节点
	if(stackempty(*s)){
        return 0;
    }else{
		*e = s -> top -> data;
		p = s -> top;		
		s -> top = s -> top -> next;		
		s -> count--;
		return 1;
	}	
}

// 遍历链栈
void visit(elementype p)
{
	printf("%d ", p);
}
bool traversestack(Linkstack s)
{
	linkstackptr p;
	p = s.top;
	while(p)
	{
		visit(p -> data);
		p = p -> next;
	}
	printf("\n");
	return true;
}

// 构造一个空栈S 
bool InitStack(Linkstack *S)
{ 
        S -> top = (linkstackptr)malloc(sizeof(stacknode));
        if(!S -> top)
                return false;
        S -> top = NULL;
        S -> count = 0;
        return true;
}

//把S置为空栈
bool ClearStack(Linkstack *S)
{ 
        linkstackptr p,q;
        p = S -> top;
        while(p)
        {  
                q = p;
                p = p -> next;
                free(q);		
        } 
        S -> count = 0;
        return true;
}

// 若栈不空，则用e返回S的栈顶元素，并返回OK；否则返回ERROR
int GetTop(Linkstack S,elementype *e)
{
        if (S.top == NULL)
                return 0;
        else
                *e = S.top -> data;
        return 1;
}

int main()
{
        int j;
        Linkstack s;
        int e;
        // 遍历链栈
        if(InitStack(&s) == true)
                for(j = 1;j <= 10;j++)
                        push(&s,j);
        printf("栈中元素依次为：");
        // 出栈
        traversestack(s);
        pop(&s,&e);
        printf("弹出的栈顶元素 e=%d\n",e);
        // 判断空栈
        printf("栈空否：%d(1:空 0:否)\n",stackempty(s));
        GetTop(s,&e);        
        return 0;
}